package org.budo.phone.freeswitch.util;

import org.budo.support.java.concurrent.executor.ExecutorUtil;
import org.freeswitch.esl.client.IEslEventListener;
import org.freeswitch.esl.client.inbound.Client;
import org.freeswitch.esl.client.inbound.InboundConnectionFailure;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
public class EslUtil {
    public static Client connectEslClient(final String host, final int port, final String password, final int timeout, IEslEventListener eventListener) {
        try {
            log.info("#103 connectEslClient, host=" + host + ", port=" + port + ", timeout=" + timeout);

            final Client client = new Client();

            // 似乎里面的超时不生效，自己做个超时
            ExecutorUtil.execute(new Runnable() {
                public void run() {
                    _esl_client_connect(client, host, port, password, timeout);
                }
            }, timeout * 1000);

            client.setEventSubscriptions("plain", "all");
            client.addEventListener(eventListener);

            log.info("#110 connectEslClient done, client=" + client + ", eventListener=" + eventListener);
            return client;
        } catch (Throwable e) {
            log.error("#138 connectEslClient error, e=" + e, e);
            return null;
        }
    }

    private static void _esl_client_connect(Client client, String host, int port, String password, int timeout) {
        try {
            client.connect(host, port, password, timeout);
        } catch (InboundConnectionFailure e) {
            throw new RuntimeException(e);
        }
    }
}